package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.clientCenter.queryBean.UserInfoQueryBean;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjMeterQuery;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工程管理-批量删除立户数据
 * 1. 删除原有pjMeterT
 * 2. 删除原有userInfoTemp
 */
public class PjMeterBatchDelete implements ServerInterface {

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjMeterQuery pjMeterQuery = JsonUtils.objectToPojo(req.getData(), PjMeterQuery.class);

            PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);

            // 1. 查出所有数据
            List<PjMeter> pjMeterList = pjMeterMapper.getList(pjMeterQuery);
            // 2. 获取所有临时用户id
            List<String> userInfoTempIdList = pjMeterList.stream().map(PjMeter::getUserInfoTempId).collect(Collectors.toList());
            // 3. 删除所有userInfoTemp
            // 20220531: 兼容userInfoTempIdList为空，直接删除整张临时表的情况
            if (userInfoTempIdList != null && userInfoTempIdList.size() >0) {
                UserInfoQueryBean userInfoQueryBean = new UserInfoQueryBean();
                userInfoQueryBean.setIdList(userInfoTempIdList);
                userInfoMapper.batchDelete(userInfoQueryBean, UserBean.USERTEMP);
            }
            // 4. 删除所有pjMeter
            pjMeterMapper.delete(pjMeterQuery);

            return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "批量删除立户数据成功", null);
        } catch (Exception e) {
            logger.error("批量删除立户数据失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "批量删除立户数据失败", null);
        }
    }
}
